package sysmiddleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/vueadmin/app/admin/internal/svc"
	sys "github.com/vueadmin/app/admin/sys"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/conv"
	"github.com/vueadmin/utils/response"
	"os"
	"path/filepath"
	"strings"
)

type DeleteMenuMiddleware struct {
	svcCtx *svc.ServiceContext
}

func NewDeleteMenuMiddleware(svcCtx *svc.ServiceContext) *DeleteMenuMiddleware {
	return &DeleteMenuMiddleware{
		svcCtx: svcCtx,
	}
}

// 删除数据表中间件
func (p DeleteMenuMiddleware) Handle() gin.HandlerFunc {
	return func(c *gin.Context) {
		var (
			data        sys.MenuReq
			menu        sys.Menu
			application sys.Application
		)
		if err := utils.BindAndValid(c, &data); err != nil {
			response.Fail(c, err.Error())
			c.Abort()
			return
		}
		if err := p.svcCtx.Db.Where("menu_id", data.MenuId).Find(&menu).Error; err != nil {
			panic(err)
		}
		if err := p.svcCtx.Db.Where("app_id", menu.AppId).Find(&application).Error; err != nil {
			panic(err)
		}
		if sys.System.GetDBTypeByConnect(menu.Connect) == "mysql" {
			prefix := sys.System.GetPrefix(menu.Connect)
			if !conv.IsEmpty(menu.Tablename) && menu.CreateTable == 1 {
				sql := fmt.Sprintf("DROP TABLE if exists %s", prefix+menu.Tablename)
				sys.System.Conn(p.svcCtx, menu.Connect).Exec(sql)
			}
		}

		currentDir, _ := os.Getwd()
		parentDir := filepath.Dir(currentDir)
		rootDir := filepath.Dir(parentDir)

		if !conv.IsEmpty(menu.ControllerName) {
			files := []string{
				rootDir + "/app/" + application.AppDir + "/internal/dto/" + conv.FirstLower(menu.ControllerName) + "Dto.go",
				rootDir + "/app/" + application.AppDir + "/internal/logic/" + conv.FirstLower(menu.ControllerName) + "Logic.go",
				rootDir + "/app/" + application.AppDir + "/internal/vo/" + conv.FirstLower(menu.ControllerName) + "Vo.go",
				rootDir + "/app/" + application.AppDir + "/internal/model/" + conv.FirstLower(menu.ControllerName) + "Model.go",
				rootDir + "/app/" + application.AppDir + "/internal/service/" + conv.FirstLower(menu.ControllerName) + "Service.go",
				rootDir + "/app/" + application.AppDir + "/internal/route/" + conv.FirstLower(menu.ControllerName) + "Route.go",
			}
			for _, v := range files {
				if utils.FileExists(v) {
					os.Remove(v)
				}
			}
			os.RemoveAll(rootDir + "/app/" + application.AppDir + "/internal/handler/" + conv.FirstLower(menu.ControllerName))
			if application.AppType == 1 {
				os.RemoveAll(rootDir + "/ui/src/views/admin/" + strings.ToLower(menu.ControllerName))
			}

			filepath := fmt.Sprintf(rootDir+"/app/%s/internal/route/routes.go", application.AppDir)
			if utils.FileExists(filepath) {
				var router string
				router = fmt.Sprintf("new(%s).RegisterRoute(r, svcCtx)\n", conv.FirstUpper(menu.ControllerName))
				utils.FilePutContents(filepath, strings.Replace(utils.FileGetContents(filepath), router, "", -1))
			}
		}
		c.Set("data", data)
		c.Next()
	}
}
